package com.itheima.app.filters;


import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AppUserAuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //白名单放行判断
        //1. 获取请求过来的url地址
        String path = request.getURI().getPath();

        //2. 判断地址是否是app的登录地址
        if(path.endsWith("/login_auth/")){
            //是则放行
            return chain.filter(exchange);
        }
        //token校验
        //1. 获取token--从请求头中获取
        String token = request.getHeaders().getFirst("token");

        //2. 非空判断
        if(StringUtils.isNotEmpty(token)){
            //3. 验证token
            int verifyToken = AppJwtUtil.verifyToken(token);
            if(SystemConstants.JWT_OK == verifyToken) {
                //获取载荷
                Claims claims = AppJwtUtil.getClaimsBody(token);
                if(null != claims) {
                    //取出id
                    Integer loginUserId = (Integer) claims.get("id");

                    //将id、头像、昵称设置进请求头中
                    request.mutate().header(SystemConstants.USER_HEADER_NAME, loginUserId.toString());

                    request.mutate().header(SystemConstants.LOGIN_USER_IMAGE,(String) claims.get("headImage"));
                    request.mutate().header(SystemConstants.LOGIN_USER_NAME,(String) claims.get("nickname"));

                    //4. 验证通过则放行
                    return chain.filter(exchange);
                }
            }
        }
        //5. 没有token，或验证未通过，阻止请求，响应未登录
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
